<!--
 * @Description: 瑞幸多选
 * @Author: Kerwin
 * @Date: 2025-05-08 16:19:21
 * @LastEditTime: 2025-11-06 14:57:55
 * @LastEditors:  Please set LastEditors
-->
<template>
    <view class="goodsChoose">

        <!-- 可选类 -->
        <view class="optionalBox" v-if="goodsItem.specifications">
            <view class="optionalItem" v-for="(item, index) in goodsItem.specifications" :key="item.id">
                <view class="goodsName">{{ item.name }}</view>
                <view class="goodsItem">
                    <view class="optional" :class="{ activeOptional: goods.checked ,disabled:!isOptionAvailable(goods.name)}"
                        @click="handleOptionalClick(item.name, goods)" v-for="(goods, index) in item.ingredients"
                        :key="goods.id">
                        <view class="name">
                            {{ goods.name }}
                        </view>
                        <!-- 售罄蒙版 -->
                        <view class="mode" v-if="goods.enable === false">
                            <view class="mode-text">售罄</view>
                        </view>
                    </view>


                </view>

            </view>

        </view>
        <!-- 提示信息 -->
        <view class="mes">
            1．划线价格：商品展示的划横线的价格是参考价格，并非商品原价而是指不参加优惠的情况下，单品门店价格的总和（单品价总和）。当套餐内容可由您选择组合时，以套餐内可选商品的最低单价总和为为划线价，该价格仅供您参考。
            说明：
            2．非划线价格指参与优惠、使用抵扣券或代金券、在活动时间或满足活动条件、按照套餐组合购买的前提下可能支付的价格，具体的成交价格可能因参加其他活动等而发生变化，最终成交价格以订单结算页价格为准。
            3．产品及包装请以实物为准，图片仅供参考
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, toRaw, toRefs, watch, nextTick } from 'vue'
import itemImg from '@/static/xfl/item.png'
//props
const props = defineProps({
    product: {
        type: Object,
        default: () => ({})
    },
    productChoose: {  //商品是否可选规则
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['chooseOptional'])
const chooseOptional = ref() //选中的小料数组种类
const otherStr = ref('')  //选中小料code 
const otherCheckStr = ref({})  //选中小料对象 
const goodsItem = ref()
const validSpecNames = ref<Set<string>>(new Set()) // 可选的规格

// 初始化可选规格
    const initValidSpecNames = () => {
  if (!goodsItem.value.sku_infos || !Array.isArray(goodsItem.value.sku_infos)) return
  goodsItem.value.sku_infos.forEach((sku: any) => {
    sku.values.forEach((value: any) => {
      validSpecNames.value.add(value.spec_name)
    })
  })
}

// 获取可选的规格名称
const isOptionAvailable = (optionName: string): boolean => {
  return validSpecNames.value.has(optionName)
}

// 选中状态变化时触发
const handleOptionalClick = (groupName: string, item: any) => {
console.log(isOptionAvailable(item.name),item.name);

    if(!isOptionAvailable(item.name)) return uni.showToast({
        title: '该小料不可选',
        icon: 'none'
    })

    goodsItem.value.specifications.forEach((group: any) => {
        if (group.name === groupName) {
            group.ingredients.forEach((ingredient: any) => {
                ingredient.checked = ingredient.name === item.name
            })
        }
    })

    // 触发计算并通知父组件
    const selectedIngredients = getSelectedIngredients()
    const matchedSku = findMatchingSku(selectedIngredients)
    console.log('匹配的sku:', matchedSku);
    
    let obj = { otherStr: matchedSku?.code, otherCheckStr: '' }
    if (matchedSku && Array.isArray(matchedSku.values)) {
        const otherCheckStr = '/' + matchedSku.values.map((v: any) => v.spec_name).join('/')
        obj.otherCheckStr = otherCheckStr
    }
    goodsItem.value.otherStr = obj.otherStr
    goodsItem.value.otherCheckStr = obj.otherCheckStr
    emit('chooseOptional',  goodsItem.value)
}

// 获取所有被选中的小料名称
const getSelectedIngredients = (): string[] => {
    const selectedNames: string[] = []

    if (!goodsItem.value.specifications) return selectedNames

    goodsItem.value.specifications.forEach((group: any) => {
        group.ingredients.forEach((ingredient: any) => {
            if (ingredient.checked) {
                selectedNames.push(ingredient.name)
            }
        })
    })
    return selectedNames
}

// 根据选中小料匹配对应的 sku
const findMatchingSku = (selectedIngredients: string[]) => {
    const { sku_infos: skus } = goodsItem.value

    if (!Array.isArray(skus)) return null

    return skus.find((sku: any) => {
        if (!Array.isArray(sku.values)) return false

        const specNames = sku.values.map((v: any) => v.spec_name)

        return (
            selectedIngredients.length === specNames.length &&
            selectedIngredients.every(name => specNames.includes(name))
        )
    })
}

// 初始化默认选中项
const initDefaultSelection = () => {
    const selectedIngredients = getSelectedIngredients()
    const matchedSku = findMatchingSku(selectedIngredients)
    let obj = { otherStr: matchedSku?.code, otherCheckStr: '' }
    if (matchedSku && Array.isArray(matchedSku.values)) {
        const otherCheckStr = '/' + matchedSku.values.map((v: any) => v.spec_name).join('/')
        obj.otherCheckStr = otherCheckStr
    }
    goodsItem.value.otherStr = obj.otherStr
    goodsItem.value.otherCheckStr = obj.otherCheckStr
    emit('chooseOptional',  goodsItem.value)
}

// 监听 product 变化，重新初始化
watch(
    () => props.product,
    (newVal) => {
        if (newVal) {
            goodsItem.value = JSON.parse(JSON.stringify(newVal))
            initValidSpecNames()
            initDefaultSelection()
        }
    },
    { immediate: true, deep: true }
)


</script>

<style lang="scss" scoped>
.goodsChoose {
    // height: calc(100vh - 400rpx);
    // margin-bottom: 1300rpx;
    background-color: #fff;

}

.goodsSize1 {

    .goodsItem {
        display: flex;
        flex-wrap: wrap;


        .required {
            width: 150rpx;
            height: 160rpx;
            border-radius: 10rpx;
            text-align: center;
            margin: 30rpx;
            // margin-bottom: 50rpx;
            border: 2rpx solid #f1f1f1;

            // .img{
            //     height: 160rpx;

            // }
            .name {
                font-size: 24rpx;
            }
        }
    }


    .goodsSize1_1 {
        font-weight: 700;
        margin: 40rpx 0;
    }

    .goodsSize1_2 {
        margin-bottom: 40rpx;
    }

}

.optionalBox {
    .optionalItem {
        .goodsItem {
            display: flex;
            flex-wrap: wrap;

            .optional {
                position: relative;
                width: 150rpx;
                height: 60rpx;
                line-height: 60rpx;
                border: 2rpx solid #f1f1f1;
                border-radius: 10rpx;
                text-align: center;
                margin: 30rpx;
                // margin-bottom: 80rpx;
                background-color: #f6f5f8;
                //color: #949496;

                .mode {
                    position: absolute;
                    top: 0;
                    width: 100%;
                    height: 100%;
                    background-color: rgba(25, 14, 14, 0.4);

                    .mode-text {
                        color: #e9e9e9;
                    }
                }

                .name {
                    font-size: 24rpx;
                }
            }
        }

    }
}


.goodsName {
    font-size: 28rpx;
    // color: #969696;
    color: #333;
    font-weight: 700;
    margin: 20rpx 0;


}

.mes {
    height: 500rpx;
    font-size: 20rpx;
    color: #969696;
    margin-top: 50rpx;
}

//选中了小料
.activeOptional {
    color: #ea7721 !important;
    border: 2rpx solid #ff6c18 !important;
    background-color: #fef1ec !important;
    /* 蓝色半透明蒙版 */
    //   opacity: 0.8; /* 可选：整体透明度控制 */
}

.disabled {
    color: #949496 !important;
}
</style>
